package CutLoad.transitions.cloud
{
	import CutLoad.Base;
	
	import flash.events.Event;
	import flash.geom.Point;

	/**
	 * 缓动跟随 
	 * @author smallerbird mail:smallerbird@gmail.com  site:www.mkigm.com QQ群:49983196
	 * 
	 */	
	public class EasingFollowMe extends Base
	{
		private var hereP:Point;
		private var target:Base;
		private var funcGetFoolwXY:Function;
		private var isStart:Boolean;
		private var easingOffset:Number;
		private var funEnterFrame:Function;
		//是否已经到达目录
		private var _isHere:Boolean;
		private var dxOver:Number,dyOver:Number;
		/**
		 * 初始化 
		 * @param target 谁要跟随
		 * @param easingOffset 缓动系数  默认为:.2
		 * @param funEnterFrame 该类循环时会调用这个方法。默认为null;  格式为：function(me:EasingFollowMe)
		 * @param dxOver 距离目标x相差值小于这个值时，表示已经到达目标  默认为:2
		 * @param dyOver 距离目标y相差值小于这个值时，表示已经到达目标  默认为:2
		 * 
		 */			
		public function EasingFollowMe(target:Base,easingOffset:Number=.2,funEnterFrame:Function=null,dxOver:Number=2,dyOver:Number=2)
		{
			hereP=new  Point();
			this.easingOffset=easingOffset
			isStart=false;
			if(funEnterFrame==null) funEnterFrame=function(me:EasingFollowMe):void{};
			this.funEnterFrame=funEnterFrame;
			this.target=target;
			this.funcGetFoolwXY=funcGetFoolwXY;
			this.addEventListener(Event.ENTER_FRAME,enter_frame);
			_isHere=false;
			this.dxOver=dxOver;
			this.dyOver=dyOver;
		}
		public function getTarget():Base{
			return target;
		}
		public function follow(p:Point):void{
			hereP=p
			_isHere=false;
		}
		public function start():void{
			isStart=true;
		}
		public function pause():void{
			isStart=false;
		}
		/**
		 * 是否已经达到目标 
		 * @return 
		 * 
		 */		
		public function get isComplete():Boolean{
			return this._isHere;
		}
		protected function enter_frame(e:Event):void{
			if(!isStart) return;
			var xx:Number=target.x;
			var yy:Number=target.y;
			//trace(easingOffset+" "+xx+" "+yy+" --> "+hereP)
			var dx:Number=hereP.x-xx;
			var dy:Number=hereP.y-yy;
			target.x+=(dx)*easingOffset;
			target.y+=(dy)*easingOffset;
			//下面这些代码不要放在funEnterFrame(this); 下面
			dx=Math.abs(dx);
			dy=Math.abs(dy);
			if(dx<dxOver&&dy<dyOver){
				target.x=hereP.x;
				target.y=hereP.y;
				_isHere=true;
			}
			//
			try{
				funEnterFrame(this);
			}catch(e:ArgumentError){
				funEnterFrame();
			}
			//
			//
		}
		override public function killMe():void{
			if(this.hasEventListener(Event.ENTER_FRAME)) this.removeEventListener(Event.ENTER_FRAME,enter_frame);
			super.killMe();
		}
		
	}
}